import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DefaultService } from '../../api';
import { HttpClient } from '@angular/common/http';
declare let BMap:any;

@Component({
  selector: 'app-device-detail',
  templateUrl: './device-detail.component.html',
  styleUrls: ['./device-detail.component.css']
})
export class DeviceDetailComponent implements OnInit {
  showRepair:boolean = false;
  repairInfo:string = "";
  id:string;
  name:string;
  serialID:string;
  location:string;
  factoryInfo:string;
  imageUrl:string;
  videoUrl:string;
  text:string;
  constructor(private router:ActivatedRoute,private next:Router,private api:DefaultService,private http:HttpClient) { }
  map:any;

  ngOnInit() {
    this.router.params.subscribe(value=>{
      this.id = value['deviceId'];
      this.api.getUser().subscribe(user=>{
        if(user.username==undefined){
          this.next.navigateByUrl('/login?go=/device/detail/'+this.id);
        }else{
          this.api.listDevices(0,1,this.id).subscribe(v=>{
            try{
              const json = JSON.parse(v[0].description);
              this.name = v[0].name;
              this.serialID = json['serialId'];
              this.location = json['location'];
              this.factoryInfo = json['factoryInfo'];
              this.imageUrl = json['imageUrl'];
              this.videoUrl = json['videoUrl'];
              this.text = json['text'];
              this.initBaiduMap()
            }catch (e) {
              console.log(e)
            }
          });
        }
      });
    });
  }

  initBaiduMap(){
    this.map = new BMap.Map("container");
    console.log(this.map);
    this.map.addControl(new BMap.NavigationControl());
    this.map.addControl(new BMap.ScaleControl());
    this.map.addControl(new BMap.OverviewMapControl());
    this.map.addControl(new BMap.MapTypeControl());
    this.map.enableScrollWheelZoom();
    this.getPointByLocation(this.location).then(value=>{
      if(value.status==0){
        console.log(value.result);
        let point = new BMap.Point(value.result.location.lng,value.result.location.lat);
        this.map.centerAndZoom(point, 15);
        let marker = new BMap.Marker(point);
        this.map.addOverlay(marker);
      }
    })
  }

  private getPointByLocation(location:string):Promise<any>{
    console.log(location);
    const api = `http://api.map.baidu.com/geocoder/v2/?address=${location}&output=json&ak=wd4Mbk6njkwfNmmr60tP0SI7l3ngOmoo&callback=callback`;
    return this.http.jsonp(api,"callback").toPromise();
  }

  repair(){
    if(!this.showRepair){
      this.showRepair = true;
      return
    }else{
      this.api.putRepair({deviceId:this.id,info:this.repairInfo}).subscribe(value=>{
        if(value.status==1){
          alert("信息以提交");
        }else{
          alert("提交失败");
          console.log(value.message);
        }
      });
      this.showRepair = false;
    }
  }

}

